<?php
declare (strict_types = 1);

namespace app\wework\listener;

use app\wework\controller\Base;
use app\wework\model\CallbackModel;
use think\facade\Db;
use app\wework\model\Helper;
use app\wework\model\QyWechatApi;
use think\facade\Log;

class CustomerDelFollow extends Base
{
    /**public
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($data)
    {
        $external_userid = $data['ExternalUserID'];
		$userid = $data['UserID'];
		$CorpID = $data['ToUserName'];
		$config = CallbackModel::getConfig($CorpID);
		$wid = $config["wid"];
		$staff = Helper::getUser(['wid'=>$wid,'userid'=>$userid]);
		$customer = Helper::getCustomer(['wid'=>$wid,'staff_id'=>$staff['id'],'external_userid'=>$external_userid]);
		$qrcode = Db::table("kt_wework_et_qrcode_statistics")->where(["wid"=>$wid,"external_userid"=>$external_userid,"staff_id"=>$staff["id"]])->find();
		if($qrcode)Db::table("kt_wework_et_qrcode_statistics")->where(["wid"=>$wid,"external_userid"=>$external_userid,"staff_id"=>$staff["id"]])->update(["type"=>2]);
		if(!$customer) return "";
		$lossing["wid"] = $wid;
		$lossing["type"] = 1;
		$lossing["external_userid"] = $external_userid;
		$lossing["staff_id"] = $staff["id"];
		$lossing["days"] = CallbackModel::dateDay($customer["createtime"]);
		$lossing["add_time"] = date("Y-m-d H:i:s",$customer["createtime"]);
		$lossing["lossing_time"] = date("Y-m-d H:i:s",time());
		$lossing["create_time"] = date("Y-m-d H:i:s",time());
		$lossing["update_time"] = date("Y-m-d H:i:s",time());
		$res = CallbackModel::lossing($lossing);
		if(!$res) return "数据库导入失败";
		$lossings["wid"] = $wid;
		$lossings["type"] = 3;
		$lossings["staff_id"] = $staff["id"];
		$lossings["customer_userid"] = $external_userid;
		$lossings["create_time"] = date("Y-m-d H:i:s",time());
		$lossings["update_time"] = date("Y-m-d H:i:s",time());
		CallbackModel::lossingSave($lossings);
		$sendContent = "客户 '{$customer["name"]}' 把你从好友列表中删除了";
		$status = Db::table('kt_wework_customer_lossing_status')->where(["wid"=>$wid])->find();
		$status = $status?$status["status"]:0;
		if($status){
			$res = QyWechatApi::send_textcard($userid,$wid,"流失提醒",$sendContent,$this->req->domain().'/wework/h5.CustomerPortrait/customer_info.html?wid='.$wid."&external_userid=".$external_userid."&staff_id=".$staff['id']);
			Log::error(json_encode($res,320));
		}
    }
}
